<template>
  <div class="employee-container">
    <h2>员工基础信息</h2>
    <!-- 查询区域：包含搜索框、查询按钮、重置按钮、新增按钮 -->
    <div class="search-container">
      <el-input
          placeholder="请输入员工姓名"
          style="width: 200px"
          v-model="queryEmployeeName"
          class="search-input"
      />
      <el-button @click="queryByEmployeeName" type="success" plain class="search-button">
        查询
      </el-button>
      <el-button
          type="default"
          class="reset-button"
          @click="resetSearch"
      >
        重置
      </el-button>
      <el-button @click="showEmployeeDialog" type="primary" class="register-button">
        新增员工
      </el-button>
    </div>

    <!-- 错误信息 -->
    <div class="error-message">{{ errorMessage }}</div>

    <!-- 员工信息表格 -->
    <el-table :data="employeeList" class="employee-table" header-cell-class-name="table-header">
      <el-table-column label="序号" type="index" width="120" align="center" />
      <el-table-column prop="employeeName" label="员工姓名" width="150" align="center" />
      <el-table-column prop="phone" label="员工电话" width="220" align="center" />
      <el-table-column prop="position" label="员工职位" width="180" align="center" />
      <el-table-column prop="hireDate" label="入职日期" width="190" align="center" :formatter="formatDate" />
      <el-table-column label="操作" width="250" align="center">
        <template #default="scope">
          <div class="button-group">
            <el-button type="primary" size="small" @click="showViewDialog(scope.row.id)">查看</el-button>
<!--            <el-button type="warning" size="small" @click="showEditDialog(scope.row.id)">职位变更</el-button>-->
            <el-button type="danger" size="small" @click="confirmRemove(scope.row.id)">辞退</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 员工信息对话框 -->
    <el-dialog v-model="employeeDialog" :title="dialogTitle" width="500">
      <el-form :model="curEmployee" label-width="90">
        <!-- 新增/编辑/查看 姓名 -->
        <el-form-item label="员工姓名" v-if="dialogOptType !== 2">
          <el-input v-model="curEmployee.employeeName" :disabled="dialogOptType === 3" />
        </el-form-item>

        <!-- 新增/查看 电话 -->
        <el-form-item label="员工电话" v-if="dialogOptType !== 2">
          <el-input v-model="curEmployee.phone" :disabled="dialogOptType === 3" />
        </el-form-item>

        <!-- 所有场景都显示职位，编辑时可改 -->
        <el-form-item label="员工职位">
          <el-select v-model="curEmployee.position" :disabled="dialogOptType === 3" style="width: 100%">
<!--            <el-option label="店长" value="店长" />-->
            <el-option label="店员" value="店员" />

          </el-select>
        </el-form-item>

        <!-- 新增/查看 入职日期 -->
        <el-form-item label="入职日期" v-if="dialogOptType !== 2">
          <el-date-picker
              v-model="curEmployee.hireDate"
              type="date"
              placeholder="选择入职日期"
              :disabled="dialogOptType === 3"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="optOne" type="primary" style="width: 100%">{{ buttonOpt }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import http from '@/axios/http';
import dayjs from 'dayjs';
import { ElMessageBox, ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue'; // 引入刷新图标

/* 数据区 */
const employeeList = ref([]);
const errorMessage = ref('');
const queryEmployeeName = ref(''); // 搜索框绑定值
const employeeDialog = ref(false);
const curEmployee = ref({});
const dialogTitle = ref('');
const buttonOpt = ref('');
const dialogOptType = ref(1); // 1 新增 2 编辑 3 查看
const pageContains = ref({ pageNum: 1, pageSize: 10, total: 0 }); // 分页信息

/* 格式化日期 */
const formatDate = (row) => (row.hireDate ? dayjs(row.hireDate).format('YYYY-MM-DD') : '');

/* 初始化：加载全部员工数据 */
onMounted(() => getAllEmployees());

/* 重置搜索：清空输入、重置分页、刷新全部数据 */
const resetSearch = () => {
  queryEmployeeName.value = ''; // 清空员工姓名搜索框
  pageContains.value.pageNum = 1; // 分页重置到第一页
  errorMessage.value = ''; // 清空错误提示
  getAllEmployees(); // 重新加载全部员工数据
};

/* 按姓名查询员工 */
const queryByEmployeeName = () => {
  http
      .post('/glsb/get_employee_by', {
        employeeName: queryEmployeeName.value,
        pageNum: pageContains.value.pageNum,
        pageSize: pageContains.value.pageSize
      })
      .then((res) => {
        if (res.data.result === 'success') {
          pageContains.value = res.data.data;
          employeeList.value = res.data.data.list;
        } else {
          errorMessage.value = res.data.error;
        }
      });
};

/* 获取全部员工数据 */
const getAllEmployees = () => {
  http
      .post('/glsb/get_all_employees', {
        pageNum: pageContains.value.pageNum,
        pageSize: pageContains.value.pageSize
      })
      .then((res) => {
        if (res.data.result === 'success') {
          pageContains.value = res.data.data;
          employeeList.value = res.data.data.list;
        } else {
          errorMessage.value = res.data.error;
        }
      });
};

/* 新增员工弹窗 */
const showEmployeeDialog = () => {
  dialogTitle.value = '新增员工';
  buttonOpt.value = '新增';
  curEmployee.value = {};
  dialogOptType.value = 1;
  employeeDialog.value = true;
};

/* 查看员工弹窗 */
const showViewDialog = (id) => {
  getEmployeeInfo(id, () => {
    dialogTitle.value = '查看员工信息';
    buttonOpt.value = '关闭';
    dialogOptType.value = 3;
    employeeDialog.value = true;
  });
};

/* 编辑员工职位弹窗 */
const showEditDialog = (id) => {
  getEmployeeInfo(id, () => {
    dialogTitle.value = '职位变更';
    buttonOpt.value = '修改';
    dialogOptType.value = 2;
    employeeDialog.value = true;
  });
};

/* 获取单个员工信息 */
const getEmployeeInfo = (id, callback) => {
  http.post('/glsb/getemployeeby_id', { id }).then((res) => {
    if (res.data.result === 'success') {
      curEmployee.value = res.data.data;
      callback && callback();
    } else {
      errorMessage.value = res.data.error;
    }
  });
};

/* 新增员工 */
const addOne = () =>
    http.post('/glsb/add_one_employee', curEmployee.value).then((res) => {
      if (res.data.result === 'success') {
        ElMessage.success('员工新增成功');
        employeeDialog.value = false;
        getAllEmployees();
      } else {
        errorMessage.value = res.data.error;
      }
    });

/* 修改员工职位 */
const modifyOne = () => {
  const { id, position } = curEmployee.value;
  http.post('/glsb/modifyemployeeby_id', { id, position }).then((res) => {
    if (res.data.result === 'success') {
      ElMessage.success('职位已更新');
      employeeDialog.value = false;
      getAllEmployees();
    } else {
      ElMessage.error(res.data.error);
    }
  });
};

/* 辞退员工 */
const removeOne = (id) =>
    http.post('/glsb/removeemployee_by_id', { id }).then((res) => {
      if (res.data.result === 'success') {
        ElMessage.success('员工已辞退');
        getAllEmployees();
      } else {
        ElMessage.error(res.data.error);
      }
    });

/* 确认辞退员工 */
const confirmRemove = (id) =>
    ElMessageBox.confirm('确定辞退该员工？', '提示', { type: 'warning' })
        .then(() => removeOne(id))
        .catch(() => ElMessage.info('已取消辞退操作'));

/* 对话框统一操作（新增/修改/关闭） */
const optOne = () => {
  if (dialogOptType.value === 1) addOne();
  else if (dialogOptType.value === 2) modifyOne();
  else employeeDialog.value = false;
};

/* 分页操作：页码变更 */
const handlePageChange = (p) => {
  pageContains.value.pageNum = p;
  // 若有搜索关键词则执行搜索，否则加载全部数据
  queryEmployeeName.value ? queryByEmployeeName() : getAllEmployees();
};

/* 分页操作：每页条数变更 */
const handleSizeChange = (s) => {
  pageContains.value.pageSize = s;
  pageContains.value.pageNum = 1; // 条数变更时重置到第一页
  queryEmployeeName.value ? queryByEmployeeName() : getAllEmployees();
};
</script>

<style scoped>
.employee-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 搜索区域布局：保证按钮间距均匀 */
.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px; /* 统一元素间距 */
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

.employee-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.table-header {
  background-color: #f8f9fa;
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 10px;
}

/*!* 重置按钮样式：hover 轻微旋转，增强交互感 *!*/
/*.reset-button {*/
/*  transition: all 0.2s ease;*/
/*}*/

/*.reset-button:hover {*/
/*  transform: rotate(5deg);*/
/*}*/
/* 新增：重置按钮样式（与搜索按钮区分，保持视觉协调） */
.reset-button {
  background: #fff;
  color: #666;
  border: 1px solid #dcdfe6;
  width: 80px;
}
.search-button:hover,
.reset-button:hover,
.register-button:hover {
  transform: translateY(-1px);
}
/* 适配小屏幕：搜索区域自动换行 */
@media (max-width: 768px) {
  .search-container {
    flex-wrap: wrap;
  }
}
</style>